package com.bootdo.clouddo.controller.book;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.task.BookTask;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.book.BookApi;
import com.bootdo.clouddo.utils.book.BookUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/book/v1/search")
public class SearchController {

    @Autowired
    private BookTask bookTask;

    @GetMapping("")
    public R search(String wd, int page) {
        try {
            JSONObject resultVo = BookUtils.fetchJSONObject(BookApi.SEARCH.getUrl() + wd + "&page=" + page);
            if(resultVo != null) {
                // 保存数据
                bookTask.saveDetailArr(resultVo.getJSONArray("list"));
                // 返回数据
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }
}
